package pl.un4giv3n.mightvsmagic.action;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import pl.un4giv3n.mightvsmagic.entity.Message;
import pl.un4giv3n.mightvsmagic.entity.User;

public class ListMessagesPageAction extends PersistenceAction{

	private static final long serialVersionUID = 1L;
	private boolean showSent;
	private List<Message> messages;
	
	@SuppressWarnings("unchecked")
	@Override
	public String execute() {
		EntityManager entityManager = getEntityManager();
		User user = getSessionUser(entityManager);
		if(user == null){
			entityManager.close();
			return LOGIN;
		}
		if(showSent){
			Query query = entityManager.createNamedQuery("find.recent.messages.by.senderId");
			query.setParameter("senderId", user.getId().longValue());
			query.setParameter("sendTime", System.currentTimeMillis()-ONE_WEEK);
			messages = query.getResultList();
		}else{
			Query query = entityManager.createNamedQuery("find.recent.messages.by.reciverId");
			query.setParameter("reciverId", user.getId().longValue());
			query.setParameter("sendTime", System.currentTimeMillis()-ONE_WEEK);
			messages = query.getResultList();
		}
		entityManager.close();
		Collections.sort(messages, new Comparator<Message>() {
		
			@Override
			public int compare(Message o1, Message o2) {
				long thisVal = o1.getSendTime();
				long anotherVal = o2.getSendTime();
				return (thisVal<anotherVal ? 1 : (thisVal==anotherVal ? 0 : -1));
			}
		});
		return SUCCESS;
	}

	public boolean isShowSent() {
		return showSent;
	}

	public void setShowSent(boolean showSent) {
		this.showSent = showSent;
	}

	public List<Message> getMessages() {
		return messages;
	}

	public void setMessages(List<Message> messages) {
		this.messages = messages;
	}
	
}
